package JZ.JZ22;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author corn
 * @create 2020-07-31-21:59
 */

/**
 * JZ22 从上往下打印二叉树
 * 题目描述
 * 从上往下打印出二叉树的每个节点，同层节点从左至右打印。
 */
public class PrintFromTopToBottom {
}
class Solution {
    public ArrayList<Integer> printFromTopToBottom(TreeNode root) {
        ArrayList<Integer> ans = new ArrayList<>();
        Queue<TreeNode> q = new LinkedList<>();
        if(root == null){
            return ans;
        }
        q.add(root);
        while(!q.isEmpty()){
            //根节点
            TreeNode r = q.poll();
            ans.add(r.val);
            //左子树
            if(r.left != null){
                q.add(r.left);
            }
            //右子树
            if(r.right != null){
                q.add(r.right);
            }
        }
        return ans;
    }
}
class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;
    }
}